<template>
  <div :class="className" :style="{height:height,width:width}"/>
</template>

<script>
import * as echarts from 'echarts'

require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    chartData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions(this.chartData)
    },
    setOptions({expectedData} = {}) {
      this.chart.setOption({
        tooltip: {
          confine: true,
          trigger: 'item',
          formatter: '{b} : {c}' // 鼠标hover时展示啥数据
        },
        legend: {
          top: '10px', // legend位置距离顶部10px
          icon: 'circle', // 将legend图标改为小圆点 // legend图标宽度
          itemWidth: 10, // legend图标宽度
          itemHeight: 10 // legend图标高度
        },
        color: ['#598EF3', '#F37C7C', '#96C807', '#7F5FFE', '#21D976'],
        series: [
          {
            avoidLabelOverlap: false,
            type: 'pie', // 图例类型：饼图
            roseType: 'area', // 玫瑰图
            top: '20px', //距离底部的距离
            center: ['50%', '50%'], // 图例在容器中的位置，第一个控制左右，第二个控制上下
            radius: ['20%', '60%'], // 20%：内部空白圆的直径，60%：外部圆环的直径
            data: expectedData,
            label: {
              normal: {
                show: true,
                textStyle: {
                  fontSize: 12,
                },
                formatter: '{b}\n-----\n{d}%\t{c}'
              },
            },
            labelLine: {
              length: 20, // 挨着图例的直线的长度
              length2: 30 // 挨着文字的直线的长度
            },
          },
        ],
      })
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
}
</script>
